
#include "../headers/OSScheduler.h"
#include <iostream>


OSScheduler::OSScheduler(vector<OSThread*> threads) :
	m_curThreadPhase(0), m_curThread(NULL), threads(threads)
{
}

bool OSScheduler::checkThreadBlocked()
{
	return m_curThread->getQuanta()==0 || m_curThread->m_yielded;
}

void OSScheduler::notifyThreadChange(OSThread *newThread)
{
	if(m_curThread!=newThread) {
		contextSwitches++;
	}
	m_curThread = newThread;

	// Save the thread's current phase
	m_curThreadPhase = m_curThread->getPhase();
}

int OSScheduler::giveQuanta(int t, int q) {
	//cout << t <<"["<<q<<"] ~~> ";
	notifyThreadChange(threads[t]);
	m_curThread->setQuanta(q);
	messageQuantoms += q;
	//cout << "OSScheduler gave "<<q <<" quantas to thread "<<t<<", waiting for him to block..."<<endl;
	do {
		usleep(100);
	} while (!checkThreadBlocked());

	return q - m_curThread->getQuanta();
}

void OSScheduler::increasePriority(int t){
}